# Controller.py
# Copyright (C) otacon 2010 <orfeo18@gmail.com>
# 
# AdSense-Monitor is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# AdSense-Monitor is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

import gobject
import gtk
import os
import sys
import webbrowser

from core import Path
from core.Configuration import Configuration
from core.ReportMonitor import *

from gui.SettingsDialog import SettingsDialog
from gui.TrayIcon import TrayIcon
from gui.TrayMenu import TrayMenu
from gui.Sound import SoundNotify
from gui.About import About
from gui.LoginDialog import LoginDialog
try:
    from gui import Notify
except:
    pass

if os.name == 'nt':
    windows = True
else:
    windows = False

class Controller():

    def __init__(self):

        self._configuration = Configuration()
        self._adsense = ReportMonitor()
        self._preferences = SettingsDialog(self._configuration)
        self._login = LoginDialog(self._configuration)
        self._about = About()
        self._traymenu = TrayMenu()
        self._report = self._configuration.get_report()
        self._sound = SoundNotify()
        options = self._configuration.get_options_dict()

        if not windows:
            self._tray = TrayIcon()
            self._notify = Notify.Notification(self._configuration)
        else:
            window = self._preferences.get_window()
            window.realize()
            self._tray = TrayIcon( window )
            self._notify = self._tray

        self._tray.set_menu(self._traymenu.get_menu())
        self.connect_signals()
        sound_file = self._configuration.get_preference('sound_file')
        if sound_file:
            self._sound.set_sound(sound_file)

        username = self._configuration.get_username()
        password = self._configuration.get_password()
        save_password = self._configuration.get_save_password()
        auto_update = self._configuration.get_auto_update()
        update_rate = self._configuration.get_update_rate()

        self._adsense.set_auto_update(auto_update)
        self._adsense.set_update_rate(update_rate)
        self._adsense.start()
        
        if not username or not password:
            self._login.open_dialog()
        else:
            self._adsense.set_credentials(username,password)

    def connect_signals(self):
        self._adsense.connect('status-changed',self.on_status_changed)
        self._adsense.connect('report-changed',self.on_report_changed)
        
        self._traymenu.connect("update-adsense", self.on_update_adsense)
        self._traymenu.connect("open-login", self.on_show_login)
        self._traymenu.connect("open-preferences", self.on_show_preferences)
        self._traymenu.connect("open-about", self.on_show_about)
        self._traymenu.connect("go-to-website", self.on_go_to_website)
        self._traymenu.connect("quit", self.on_close)
        
        self._configuration.connect("config-changed", self.on_settings_changed)
    
    def on_status_changed(self,caller,status):
        self._tray.on_status_changed(status)
        if status == -1:
            self._traymenu.refresh_enabled(False)
            self._login.open_dialog()
        if status == 1:
            self._traymenu.refresh_enabled(False)
        if status == 0:
            self._traymenu.refresh_enabled(True)
        
    def on_show_preferences(self,args):
        self._preferences.open_dialog()

    def on_show_login(self,args):
        self._login.open_dialog()

    def on_show_about(self,args):
        self._about.show()
        
    def on_update_adsense(self,args):
        self._adsense.update()

    def on_close(self,args):
        self._tray.remove()
        self._adsense.exit()
        gtk.main_quit()
        sys.exit(0)

    def on_report_changed(self, reportmonitor , report_row):
        earnings = str( report_row.get_earnings() )
        ecpm = str( report_row.get_ecpm() )
        impressions = str( report_row.get_impressions() )
        clicks = str( report_row.get_clicks() )
        ctr = str( report_row.get_ctr() )
        report_time = str( report_row.get_day() )
        differences = self._report.get_differences( report_row )
        tooltip_enabled = self._configuration.get_update_tooltip()
        sound_enabled = self._configuration.get_play_sound()
        popups_enabled = self._configuration.get_show_popups()

        message = 'Adsense-Monitor\n'

        if self._configuration.get_show_earnings():
            message+= 'Earnings: ' + earnings + '\n'

        if self._configuration.get_show_ecpm():
            message+= 'eCPM: ' + ecpm + '\n'

        if self._configuration.get_show_impressions():
            message+= 'Impressions: ' + impressions + '\n'

        if self._configuration.get_preference('show_clicks'):
            message+= 'Clicks: ' + clicks + '\n'

        if self._configuration.get_show_ctr():
            message+= 'CTR: ' + ctr + '\n'

        if self._configuration.get_show_report_time():
            message+= 'Report Day: ' + report_time

        
        if message and tooltip_enabled:
            message = message.strip('\n')
            self._tray.set_tooltip(message)

        message = ''
        play_sound = False

        if 'Earnings' in differences:
            if self._configuration.get_notify_earnings():
                message+= 'Earnings: ' + earnings + '\n'
            if self._configuration.get_sound_earnings():
                play_sound = True

        if 'eCPM' in differences:
            if self._configuration.get_notify_ecpm():
                message+= 'eCPM: ' + ecpm + '\n'
            if self._configuration.get_sound_ecpm():
                play_sound = True

        if 'Impressions' in differences:
            if self._configuration.get_notify_impressions():
                message+= 'Impressions: ' + impressions + '\n'
            if self._configuration.get_sound_impressions():
                play_sound = True

        if 'Clicks' in differences:
            if self._configuration.get_notify_clicks():
                message+= 'Clicks: ' + clicks + '\n'
            if self._configuration.get_sound_clicks():
                play_sound = True

        if 'CTR' in differences:
            if self._configuration.get_notify_ctr():
                message+= 'Earnings: ' + ctr + '\n'
            if self._configuration.get_sound_ctr():
                play_sound = True

        if 'Report Time' in differences:
            if self._configuration.get_notify_report_time():
                message+= 'Report Day: ' + report_time + '\n'
            if self._configuration.get_sound_ctr():
                play_sound = True

        if message and popups_enabled:
            message = message.strip('\n')
            self._notify.show_notify(message)

        if play_sound and sound_enabled:
            self._sound.play()

        self._report = report_row
        self._configuration.set_report( report_row )
        return

    def on_settings_changed(self,dialog,preferences):
        force_update = False
        if 'username' in preferences or 'password' in preferences:
            username = preferences['username']
            password = preferences['password']
            self._adsense.set_credentials(username,password)
            force_update = True
            
        for name in preferences:
            if name == 'auto_update':
                self._adsense.set_auto_update(preferences[name])
            elif name == 'update_rate':
                self._adsense.set_update_rate(preferences[name])
            elif name == 'sound_file':
                    self._sound.set_sound(preferences[name])
            elif name == 'show_popups':
                self._tray.set_tooltip('Adsense-Monitor')
        if force_update:
            self._adsense.update()
        
    def on_go_to_website(self,data):
        website = 'http://adsense-monitor.blogspot.com/p/downloads.html'
        webbrowser.open(website,2,True)
